﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace WPFSample.CalculateInHexSample
{
    class RoundedButtonDecorator : Decorator
    {
        public bool IsPressed
        {
            get { return (bool)GetValue(IsPressedProperty); }
            set { SetValue(IsPressedProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsPressed.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsPressedProperty =
            DependencyProperty.Register("IsPressed", typeof(bool), typeof(RoundedButtonDecorator), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsRender));

        protected override Size MeasureOverride(Size constraint)
        {
            Size szDesired = new Size(2, 2);
            constraint.Width -= 2;
            constraint.Height -= 2;
            if (this.Child != null)
            {
                this.Child.Measure(constraint);
                szDesired.Width += this.Child.DesiredSize.Width;
                szDesired.Height += this.Child.DesiredSize.Height;
            }

            return szDesired;
        }

        protected override Size ArrangeOverride(Size arrangeSize)
        {
            if (this.Child != null)
            {
                Point ptChild = new Point(Math.Max(1, (arrangeSize.Width - this.Child.DesiredSize.Width) / 2),
                    Math.Max(1, (arrangeSize.Height - this.Child.DesiredSize.Height) / 2));
                this.Child.Arrange(new Rect(ptChild, this.Child.DesiredSize));
            }

            return arrangeSize;
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            RadialGradientBrush brush = new RadialGradientBrush(this.IsPressed ? SystemColors.ControlDarkColor : SystemColors.ControlLightColor,
                SystemColors.ControlColor);
            brush.GradientOrigin = this.IsPressed ? new Point(0.75, 0.75) : new Point(0.25, 0.25);
            drawingContext.DrawRoundedRectangle(brush,
                new Pen(SystemColors.ControlDarkBrush, 1),
                new Rect(new Point(0, 0), this.RenderSize),
                this.RenderSize.Height / 2,
                this.RenderSize.Height / 2);
        }
    }
}
